package com.aimei520.controller.intercepter;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

import com.aimei520.po.admin.Url;
import com.aimei520.utils.JsonResult;

/**
 * 权限校验
 * Title: AccessInterceptor.java
 * Description:  
 * Copyright: Copyright (c) 2018
 * Company: www.storyboy.xyz 
 * @author JiaXun  
 * @date 2018年9月6日  
 * @version 1.0.0
 */
public class AccessInterceptor extends HandlerInterceptorAdapter{

	private UrlPathHelper urlPathHelper = new UrlPathHelper();
	 
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		String url = urlPathHelper.getLookupPathForRequest(request);
		
		@SuppressWarnings("unchecked")
		List<Url> urls = (List<Url>)request.getSession().getAttribute("url");
		if(request.getMethod().equals("POST")) {
			
			if(!testAccess(urls,url)) {
				
				JsonResult jsonResult = new JsonResult(false,"你没有该权限");
				response.setHeader("content-type", "text/html;charset=UTF-8");
				response.getWriter().write(jsonResult.toJson());
				
				return false;
			}
			
		}else {
			if(!testAccess(urls,url)) {
				response.sendRedirect(request.getContextPath()+"/login/error");
				return false;
			}
		}
		
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		super.postHandle(request, response, handler, modelAndView);
	}

	/**
	 * 权限校验
	 * @param urls
	 * @param url
	 * @return
	 */
	private boolean testAccess(List<Url> urls ,String url) {
		
		for (Url menu2 : urls) {
			
			if( menu2.getUrl().equals(url) )
				return true;
			
		}
		
		return false;
	}
	

	
	
}
